import 'dart:io';

import 'package:dio_cache_interceptor_hive_store/dio_cache_interceptor_hive_store.dart';
import 'package:get/get.dart';
import 'package:safetymonitor/app/core/constans/storage.dart';
import 'package:safetymonitor/app/core/utils/log_util.dart';
import 'package:safetymonitor/app/core/utils/storage_util.dart';
import 'package:safetymonitor/app/data/entities/auth/user_profile_entity.dart';
import 'package:safetymonitor/router/app_pages.dart';

abstract class UserManager {
  static void init() {
    _isLoggedIn = getToken() != null && getUser() != null;
    // _isLoggedIn =  getUser() != null;
  }

  /// 用户信息, 可利用 ObxValue 监听数据变化
  static final _userEntity = Rxn<UserProfileEntity>();

  static String? _token;
  static String? _companyName;
  static String? _username;
  static String? _password;
  static int? _companyId;

  static late bool _isLoggedIn;

  static Rxn<UserProfileEntity> get rxUserEntity => _userEntity;

  /// 是否登录了
  static bool get isLoggedIn => _isLoggedIn;


  /// 退出登录，清空缓存数据
  static void logout() async {
    await clearDioCache();
    AppLogger.log('[UserManager.logout()] 退出登录，清除用户信息');
    removeUserInfo();
  }

  /// 清除和重置相关用户数据
  static void removeUserInfo() {
    _isLoggedIn = false;
    _token = null;
    _companyName = null;
    _username = null;
    _password = null;
    _userEntity.value = null;
    StorageUtil.removeAll([StorageConstants.userInfo, StorageConstants.authenticationToken,StorageConstants.appMiddleModuleList]);
    Get.offAllNamed(Routes.authLogin);
  }

  /// 清除token
  static void removeToken() {
    _token = null;
    StorageUtil.removeAll([StorageConstants.authenticationToken]);
  }

  /// 清除dio缓存
  static Future<void> clearDioCache() async {
    // await MemCacheStore().clean();
    // 清理磁盘缓存
    await HiveCacheStore(Directory.systemTemp.path).clean();
  }

  /// 进行登录
  static void login(UserProfileEntity userEntity, String username) {
    _isLoggedIn = true;
    _userEntity.trigger(userEntity);
    // saveUser(userEntity).whenComplete(() {
    // ... 继续其他设置, 例如埋点
    // });
  }

  /// 保存用户信息
  static Future<void> saveUser(UserProfileEntity userEntity) async {
    _isLoggedIn = true;
    _userEntity.trigger(userEntity);
    await StorageUtil.setJSON(StorageConstants.userInfo, userEntity.toJson());
  }

  static UserProfileEntity? getUser() {
    _userEntity.value ??= StorageUtil.getEntity<UserProfileEntity>(StorageConstants.userInfo);
    return _userEntity.value;
  }

  static Future<void> saveToken(String? token) async {
    if (token != null) {
      _token = token;
      await StorageUtil.setString(StorageConstants.authenticationToken, token);
    }
  }
 //公司名
  static Future<void> saveUserCompanyName(String? companyName) async {
    if (companyName != null) {
      _companyName = companyName;
      await StorageUtil.setString(StorageConstants.saveUserCompanyName, companyName);
    }
  }
  //登录账号username
  static Future<void> saveUsername(String? username) async {
    if (username != null) {
      _username = username;
      await StorageUtil.setString(StorageConstants.saveUsername, username);
    }
  }
  static String? getUsername() {
    _username ??= StorageUtil.getString(StorageConstants.saveUsername);
    return _username;
  }

  //登录密码
  static Future<void> savePassword(String? password) async {
    if (password != null) {
      _password = password;
      await StorageUtil.setString(StorageConstants.savePassword, password);
    }
  }
  static String? getPassword() {
    _password ??= StorageUtil.getString(StorageConstants.savePassword);
    return _password;
  }

  //公司id
  static Future<void> saveUserCompanyID(int? id) async {
    if (id != null) {
      _companyId = id;
      await StorageUtil.setInt(StorageConstants.saveUserCompanyId, id);
    }
  }
  static String? getToken() {
    _token ??= StorageUtil.getString(StorageConstants.authenticationToken);
    return _token;
  }
  static String? getUserCompanyName() {
    _companyName ??= StorageUtil.getString(StorageConstants.saveUserCompanyName);
    return _companyName;
  }
  static int? getUserCompanyId() {
    _companyId??= StorageUtil.getInt(StorageConstants.saveUserCompanyId);
    return _companyId;
  }
 ///保存安全生产数据 4个
 //  static Future<void>  saveUserSafeCompanyEntity(List<EnvCompanyTreeEntity> userEntity) async {
 //    await StorageUtil.setJSON(StorageConstants.envCompanyTreeEntity, userEntity);
 //  }
 //
 //  static List<EnvCompanyTreeEntity> getUserSafeCompanyEntity() {
 //    return  StorageUtil.getEntity<List<EnvCompanyTreeEntity>>(StorageConstants.envCompanyTreeEntity)??[];
 //  }
  ///保存环境监测数据 3个
  // static Future<void>  saveUserEnvCompanyEntity(List<EnvCompanyTreeEntity> userEntity) async {
  //   await StorageUtil.setJSON(StorageConstants.envSafeCompanyTreeEntity, userEntity);
  // }
  //
  // static List<EnvCompanyTreeEntity> getUserEnvCompanyEntity() {
  //   return  StorageUtil.getEntity<List<EnvCompanyTreeEntity>>(StorageConstants.envSafeCompanyTreeEntity)??[];
  // }


  /// 调用网络接口请求用户信息
  static Future<bool> requestUserInfo() async {
    // 请求接口
    // 保存用户信息
    return true;
  }

  static int? getUserId() {
    return _userEntity.value?.id;
  }

  static bool isCurrentUser(int? userId) => getUserId() == userId;

}
